#include "configset.h"
#include "ui_configset.h"
#include "jsonparse.h"

ConfigSet::ConfigSet(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ConfigSet)
{
    ui->setupUi(this);
}

ConfigSet::~ConfigSet()
{
    delete ui;
}

void ConfigSet::showPage(ConfigSet::Page p)
{
    ui->stackedWidget->setCurrentIndex(p);
    // 判断当前page是客户端还是服务器
    if(p == Client)
    {
        // 读磁盘的配置文件, 将文件中的信息初始化到窗口中
        CliConfig conf = JsonParse::getInstance()->readClientConfig();
        // 窗口数据设置
        ui->clientid->setText(conf.clientID);
        ui->serverid->setText(conf.serverID);
        ui->ip->setText(conf.ip);
        ui->port->setText(conf.port);
        ui->shmkey->setText(conf.shmKey);
    }
    else
    {
        // 服务器的配置窗口
        SerConfig cfg = JsonParse::getInstance()->readServerConfig();
        ui->id_server->setText(cfg.serverID);
        ui->port_server->setText(cfg.port);
        ui->dbAddr->setText(cfg.dbHost);
        ui->dbPort->setText(cfg.dbPort);
        ui->dbName->setText(cfg.dbName);
        ui->dbUserName->setText(cfg.dbUserName);
        ui->dbPasswd->setText(cfg.dbPasswd);
        ui->shmNodeNum->setText(cfg.shmMaxNode);
        ui->shmkey_server->setText(cfg.shmKey);
    }
}

void ConfigSet::on_okBtn_clicked()
{
    // 将窗口中用户输出的信息读出, 写入到磁盘文件中
    CliConfig conf;
    conf.clientID = ui->clientid->text();
    conf.serverID = ui->serverid->text();
    conf.ip = ui->ip->text();
    conf.port = ui->port->text();
    conf.shmKey = ui->shmkey->text();

    // 使用单例对象, 将数据写入到文件中
    JsonParse::getInstance()->writeClientConfig(conf);

    emit goback();
}

void ConfigSet::on_cancelBtn_clicked()
{
    emit goback();
}

void ConfigSet::on_commitBtn_clicked()
{
    // 组织数据
    SerConfig cfg;
    cfg.serverID = ui->id_server->text();
    cfg.port = ui->port_server->text();
    cfg.dbHost = ui->dbAddr->text();
    cfg.dbPort = ui->dbPort->text();
    cfg.dbName = ui->dbName->text();
    cfg.dbUserName = ui->dbUserName->text();
    cfg.dbPasswd = ui->dbPasswd->text();
    cfg.shmMaxNode = ui->shmNodeNum->text();
    cfg.shmKey = ui->shmkey_server->text();

    // 写文件
    JsonParse::getInstance()->writeServerConfig(cfg);
    emit goback();
}

void ConfigSet::on_cancel_s_Btn_clicked()
{
    emit goback();
}
